<?php
namespace app\weixin\controller;
use app\weixin\controller\BaseController;
use app\weixin\model\WeixinUser;
class UserController extends BaseController {
  public function _initialize($skip_action = []){
    $skip_action = [];
    parent::_initialize($skip_action);

    $this->openid = $this->request->param("openid");
    if(empty($this->openid)){
      $current_weixin_user = session_current_weixin_user();
      if($current_weixin_user){
        $this->openid = $current_weixin_user["openid"];
      }
    }

    if(empty($this->openid)){
      exit();
    }else{
      $this->Model = new WeixinUser();
    }
  }

  public function index(){
    $user_info = $this->Model->getOauthUserinfo($this->openid);
    return json($user_info);
  }

  //获取用户授权信息
  public function show(){
    $user_info = $this->Model->getOauthUserinfo($this->openid);
    return json($user_info);
  }

  //通过openid获取关注状态判断是否是公众号粉丝
  public function is_fans(){
    $user_info = $this->Model->getUserinfo($this->openid);
    $subscribe = 0;
    if(empty($user_info["errcode"])){
      $subscribe = intval($user_info["subscribe"]);
    }
    $result = array("subscribe" => $subscribe);
    return json($result);
  }

  //手动清空用户session
  public function clear(){
    $current_weixin_user = session_current_weixin_user();
    if($current_weixin_user["openid"] == $this->openid){
      // 如果被清除的用户正好是当前授权用户，同时清除当前授权用户
      session_current_weixin_user(null);
    }
    session_weixin_user($this->openid, null);
    // 清除app绑定信息
    session("is_binded", null);

    $result = array(
      "openid" => $this->openid,
      "user" => session_weixin_user($this->openid),
      "current_user" => session_current_weixin_user(),
    );
    return json($result);
  }
}